<template>
  <div>
    <h1>商品列表</h1>
  </div>
  <el-form :model="searchForm" :inline="true">
    <el-form-item label="商品名称">
      <el-input v-model="searchForm.keyWord"></el-input>
    </el-form-item>
    <el-form-item label="商品id">
      <el-input v-model="searchForm.prodId"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="loadList">搜索</el-button>
    </el-form-item>
  </el-form>
  <el-button type="warning" @click="batachDelete()">批量删除</el-button>
  <el-form-item>
    <el-button type="primary" @click="toSaveprod()">添加商品</el-button>
  </el-form-item>
  <div>
    <el-table
      :data="tableData"
      style="width: 100%"
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="商品id" width="180" />
      <el-table-column prop="prodSpu" label="商品spu" width="180" />
      <el-table-column prop="prodKind" label="商品类型">
        <template #default="scope">
          <span v-if="scope.row.prodKind == 0">实物商品</span>
          <span v-if="scope.row.prodKind == 1">虚拟商品</span>
          <span v-if="scope.row.prodKind == 2">卡密/网盘</span>
        </template>
      </el-table-column>
      <el-table-column prop="prodType" label="商品分类">
        <template #default="scope">
          <span v-if="scope.row.prodType == 1">手机数码</span>
          <span v-if="scope.row.prodType == 2">电脑办公</span>
          <span v-if="scope.row.prodType == 3">其它</span>
        </template>
      </el-table-column>
      <el-table-column prop="prodName" label="商品名称" />
      <el-table-column prop="createBy" label="创建人" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="unitId" label="单位 ">
        <template #default="scope">
          <span v-if="scope.row.unitId == 1">台</span>
          <span v-if="scope.row.unitId == 2">个</span>
          <span v-if="scope.row.unitId == 3">其它</span>
        </template>
      </el-table-column>
      <el-table-column prop="tagId" label="商品标签 " />
      <el-table-column prop="appr" label="供应商 " />
      <el-table-column prop="prodImage" label="商品图片 ">
        <template #default="scope">
          <el-image
            :src="scope.row.prodImage"
            style="width: 70px; height: 70px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作 ">
        <template #default="scope">
          <el-button type="success" @click="prodFu(scope.row)"
            >商品附件</el-button
          >
          <el-button type="info" @click="prodInfo(scope.row)"
            >商品详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="searchForm.pageNum"
      v-model:page-size="searchForm.pageSize"
      :page-sizes="[1, 2, 3, 4]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="dialogFormVisible" title="Shipping address" width="800">
    <el-form :model="saveForm" :rules="rules" ref="ruleFormRef">
      <el-form-item label="商品类型" prop="prodKind">
        <el-radio-group v-model="saveForm.prodKind">
          <el-radio :value="0">实物物流</el-radio>
          <el-radio :value="1">虚拟商品</el-radio>
          <el-radio :value="2">卡密/网盘</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="商品分类"
        :label-width="formLabelWidth"
        prop="prodType"
      >
        <el-select v-model="saveForm.prodType" placeholder="请选择">
          <el-option label="笔记本" :value="1" />
          <el-option label="手机" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品品牌" :label-width="formLabelWidth">
        <el-select v-model="saveForm.brandId" placeholder="请选择">
          <el-option
            v-for="item in BrandOptions"
            :label="item.brandName"
            :value="item.brandId"
            :key="item.brandId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="商品名称"
        :label-width="formLabelWidth"
        prop="prodName"
      >
        <el-input v-model="saveForm.prodName" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="商品SPU"
        :label-width="formLabelWidth"
        prop="prodSpu"
      >
        <el-input v-model="saveForm.prodSpu" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="商品单位"
        :label-width="formLabelWidth"
        prop="unitId"
      >
        <el-select v-model="saveForm.unitId" placeholder="请选择">
          <el-option label="台" :value="1" />
          <el-option label="个" :value="2" />
          <el-option label="其它" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" :label-width="formLabelWidth">
        <el-select v-model="saveForm.tagId" placeholder="请选择">
          <el-option label="红" :value="1" />
          <el-option label="黄" :value="2" />
          <el-option label="蓝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商名称" :label-width="formLabelWidth">
        <el-input v-model="saveForm.appr" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" prop="prodImage">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:10010/team/index/uploadImage"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="headers"
        >
          <img
            v-if="saveForm.prodImage"
            :src="saveForm.prodImage"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogFuJianVisible" title="Shipping address" width="500">
    <el-form :model="fuForm" :rules="rules" ref="ruleFormRef">
      <el-form-item label="轮播图" prop="fileList">
        <el-upload
          v-model:file-list="fileList"
          action="http://localhost:10010/team/index/uploadImage"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :headers="headers"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="上传视频">
        <el-upload
          :v-model="fuForm.attaVideo"
          ref="upload"
          class="upload-demo"
          action="http://localhost:10010/team/index/uploadImage"
          :limit="1"
          :on-exceed="handleExceed"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>

          <template #tip>
            <div class="el-upload__tip text-red">
              limit 1 file, new file will cover the old file
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="上架时间" prop="upFlag">
        <el-radio-group v-model="fuForm.upFlag">
          <el-radio :value="0">立即上架</el-radio>
          <el-radio :value="1">定时上架</el-radio>

          <div class="demo-datetime-picker">
            <div class="block" v-if="fuForm.upFlag == 1">
              <el-date-picker
                v-model="fuForm.upTime"
                type="datetime"
                placeholder="Select date and time"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </div>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="定时下架">
        <el-tooltip
          :content="'Switch value: ' + fuForm.downFlag"
          placement="top"
        >
          <el-switch
            v-model="fuForm.downFlag"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            active-value="1"
            inactive-value="0"
          />
        </el-tooltip>
        <div class="demo-datetime-picker">
          <div class="block" v-if="fuForm.downFlag == 1">
            <el-date-picker
              v-model="fuForm.downTime"
              type="datetime"
              placeholder="Select date and time"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFuJianVisible = false">Cancel</el-button>
        <el-button type="primary" @click="saveAtta()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { ComponentSize } from "element-plus";
const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);
import { onMounted, ref } from "vue";
const tableData = ref([]);
import {
  getProdList,
  batachDel,
  getBrandList,
  brandList,
  saveProdAtta,
  saveProd,
} from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
const total = ref(0);
const searchForm = ref({
  pageSize: 3,
  pageNum: 1,
  keyWord: "",
  prodId: null,
});
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const rules = ref<FormRules>({
  prodKind: [{ required: true, message: "请选择商品类型", trigger: "blur" }],
  prodType: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  prodName: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请选择商品prodSpu", trigger: "blur" }],
  unitId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  prodImage: [{ required: true, message: "请选择商品图片", trigger: "change" }],
  fileList: [{ required: true, message: "请上传轮播图片", trigger: "change" }],
  upFlag: [{ required: true, message: "请选择上架时间", trigger: "blur" }],
  // prodType: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
});
const loadList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("展示成功");
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};
onMounted(() => {
  loadList();
  BrandList();
});
const router = useRouter();
import type { TableInstance } from "element-plus";
import { useRouter } from "vue-router";
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

const batachDelete = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning("请先选择数据");
    return;
  }

  ElMessageBox.confirm("删除后无法恢复确认删除吗?", "Warning", {
    confirmButtonText: "删除",
    cancelButtonText: "关闭",
    type: "warning",
  })
    .then(() => {
      batachDel(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const dialogFuJianVisible = ref(false);
const formLabelWidth = "140px";
const saveForm = ref({
  appr: "",
  brandId: null,
  createBy: "",
  createTime: "",
  prodId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodType: null,
  tagId: null,
  unitId: null,
  updateBy: "",
  updateTime: "",
});

const fuForm = ref({
  attaId: null,
  attaImages: "",
  attaVideo: "",
  createBy: "",
  createTime: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
  updateBy: "",
  updateTime: "",
  fileList: [],
});
const toSaveprod = () => {
  saveForm.value = {
    appr: "",
    brandId: null,
    createBy: "",
    createTime: "",
    prodId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodType: null,
    tagId: null,
    unitId: null,
    updateBy: "",
    updateTime: "",
  };
  saveForm.value.prodImage = "";
  dialogFormVisible.value = true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");

      saveProd(saveForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

import type { UploadProps } from "element-plus";

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  saveForm.value.prodImage = response.data;
};
const BrandOptions = ref([]);
const BrandList = () => {
  getBrandList().then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("品牌展示成功");
      BrandOptions.value = res.data.data;
    }
  });
};

//轮播图
import type { UploadUserFile } from "element-plus";
const fileList = ref<UploadUserFile[]>();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const prodFu = (row: any) => {
  fuForm.value = {
    attaId: null,
    attaImages: "",
    attaVideo: "",
    createBy: "",
    createTime: "",
    downFlag: null,
    downTime: "",
    prodId: row.prodId,
    upFlag: null,
    upTime: "",
    updateBy: "",
    updateTime: "",
    fileList: [],
  };

  dialogFuJianVisible.value = true;
};

//上传视频
import { genFileId } from "element-plus";

import type { UploadInstance, UploadRawFile } from "element-plus";

const upload = ref<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const saveAtta = () => {
  saveProdAtta(fuForm.value).then((res) => {
    let attaImagesList: any = [];
    fileList.value.forEach((item) => {
      console.log("item", item.response.data);
      attaImagesList.push(item.response.data);
    });
    fuForm.value.attaImages = JSON.stringify(attaImagesList);
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFuJianVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const prodInfo = (row: any) => {
  router.push("/home/prodInfo/" + row.prodId);

  console.log("prodId", row.prodId);
};
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
